package models

import "github.com/astaxie/beego/orm"

type CategoryQueryParam struct {
	BaseQueryParam
}

type Category struct {
	Id           int
	CategoryName string
	ParentId     int
	ListOrder    int
	SysUser      *SysUser `orm:"rel(fk)"`
	Thumb        string
	AddTime      int64
}

func init() {
	orm.RegisterModel(new(Category))
}

func (u *Category) TableName() string {
	return CategoryTBName()
}

func CategoryTBName() string {
	return TableName("category")
}

func CategoryOne(id int) (*Category, error) {
	m := Category{Id: id}
	o := orm.NewOrm()

	var err error
	err = o.Read(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}

func CategoryPageList(params *CategoryQueryParam) ([]*Category, int64) {
	query := orm.NewOrm().QueryTable(CategoryTBName())
	data := make([]*Category, 0)

	sort := "Id"

	switch params.Sort {
	case "Id":
		sort = "Id"
	}

	if params.Order == "desc" {
		sort = "-" + sort
	}

	total, _ := query.Count()
	query.Limit(params.Limit, params.Offset).All(&data)

	return data, total
}

func CategoryDataList(params *CategoryQueryParam) []*Category {
	params.Limit = -1
	params.Sort = "Id"
	params.Order = "asc"
	data, _ := CategoryPageList(params)
	return data
}
